<?php
declare(strict_types=1);

namespace App\Model\Service;

use App\Cache\RedisKey;
use App\Constants\ErrorCode;
use App\Helpers\RedisUtil;
use App\Model\Act\HostTaskReward;
use App\Model\Act\ProfileRewardLog;
use App\Model\Message;
use App\Model\UserAutoMsg;
use App\Model\UserProfile;
use App\Model\Withdraw;

/**
 * 新人女用户回复得礼包
 */
class NewGirlReplyPackageService
{
    // 回复第一次奖励
    const FIRDT_REPLY_POP = 1;

    // 第三次发言检查搭讪是否填写
    const AUTO_MSG_POP = 2;

    // 第5次发言检查资料是否填写完整（未完成）
    const USER_INFO_POP = 3;

    // 第5次发言检查资料是否填写完整（完善资料之后）
    const FINISH_SER_INFO_POP = 4;

    // 首次达到提现门槛，弹框提示
    const CAN_WITHDRAW_POP = 5;

    // 真人认证
    const REAL_AVATAR_POP = 6;

    /** 获取用户发送消息数量
     * @param int $userId
     * @return int
     * @throws \RedisException
     */
    public static function getGirlSendTotal(int $userId): int
    {
        $key = RedisKey::getUserMsgNum($userId);

        $redis = RedisUtil::getRedis();

        return (int)($redis->zScore($key, 0));
    }

    /**
     * 真人认证
     * @param int $userId
     * @return bool
     * @throws \RedisException
     */
    public static function realAvatar(int $userId): bool
    {
        if (!UserProfile::checkAvatarVrfied($userId)) {
            return false;
        }

        if (self::checkPopDemonstrated($userId, self::REAL_AVATAR_POP)) {
            return true;
        }

        // 已经完成过的任务，不再弹出
        if (HostTaskReward::checkDone($userId, 'real_avatar')) {
            return true;
        }

        // 真人认证
        Message::sendSlient($userId, 'REAL_AVATAR_POP', [
            'coin'       => 7,
            'waitTitle'  => '恭喜你完成真人认证',
            'waitDesc_1' => '可领取',
            'waitDesc_2' => '金币',
            'waitDesc_3' => '金币可提现',
            'waitIcon'   => '',
            'title'      => '恭喜你完成真人认证',
            'desc_1'     => '金币已存入你的账户',
            'desc_2'     => '金币可提现',
            'icon'       => '',
            'task_type'  => 'real_avatar'
        ]);

        HostTaskReward::addRecord($userId, 'real_avatar', 7);

        return true;
    }

    /**
     * 回复第一次奖励
     * @param int $userId
     * @return bool
     * @throws \RedisException
     */
    public static function firstReplyReward(int $userId): bool
    {
        $sendTotal = self::getGirlSendTotal($userId);

        if ($sendTotal < 1) {
            return false;
        }

        if (self::checkPopDemonstrated($userId, self::FIRDT_REPLY_POP)) {
            return true;
        }

        // 首次回复男用户
        Message::sendSlient($userId, 'NEW_GIRL_REPLY', [
            'coin'       => 3,
            'waitTitle'  => '回复用户领金币',
            'waitDesc_1' => '可领取',
            'waitDesc_2' => '金币',
            'waitDesc_3' => '金币可提现',
            'waitIcon'   => '',
            'title'      => '恭喜你完成回复用户任务',
            'desc_1'     => '金币已存入你的账户',
            'desc_2'     => '金币可提现',
            'icon'       => '',
            'task_type'  => 'msg_back'
        ]);

        HostTaskReward::addRecord($userId, 'say_hi', 3);

        return true;
    }

    /**
     * 第三次发言检查搭讪是否填写
     * @param int $userId
     * @return bool
     */
    public static function checkAutoMsg(int $userId): bool
    {
        $sendTotal = self::getGirlSendTotal($userId);
        if ($sendTotal < 2) {
            return true;
        }

        if (self::checkPopDemonstrated($userId, self::AUTO_MSG_POP)) {
            return true;
        }

        $autoMsg = UserAutoMsg::getUserMsgs($userId);
        if (!empty($autoMsg)) {
            return true;
        }

        // 挂断消息
        Message::sendSlient($userId, 'USER_AUTO_MSG');

        return true;
    }

    /**
     * 第5次发言检查资料是否填写完整(未填写弹框)
     * @param int $userId
     * @return bool
     */
    public static function checkUserInfo(int $userId): bool
    {
        $sendTotal = self::getGirlSendTotal($userId);
        if ($sendTotal < 4) {
            return true;
        }

        $profile = UserProfile::getProfile($userId, false, false);

        if (UserProfile::checkProfileComplete($profile)) {
            return true;
        }

        if (self::checkPopDemonstrated($userId, self::USER_INFO_POP)) {
            return true;
        }

        // 已经完成过的任务，不再弹出
        if (HostTaskReward::checkDone($userId, 'fix_profile')) {
            return true;
        }

        // 挂断消息
        Message::sendSlient($userId, 'IMPROVE_INFO', [
            'coin'       => 5,
            'title'      => '完善资料领金币',
            'desc_1'     => '完善资料后可领取',
            'desc_2'     => '金币',
            'icon'       => '',
        ]);

        return true;
    }

    /**
     * 第5次发言检查资料是否填写完整(完善资料弹框)
     * @param int $userId
     * @return bool
     */
    public static function checkFinishUserInfo(int $userId): bool
    {
        $profile = UserProfile::getProfile($userId, false, false);

        if (UserProfile::checkProfileComplete($profile) == 0) {
            return true;
        }

        if (self::checkPopDemonstrated($userId, self::FINISH_SER_INFO_POP)) {
            return true;
        }

        // 已经完成过的任务，不再弹出
        if (HostTaskReward::checkDone($userId, 'fix_profile')) {
            return true;
        }

        // 挂断消息
        Message::sendSlient($userId, 'IMPROVE_INFO_FINISH', [
            'coin'       => 5,
            'waitTitle'  => '完成完善资料任务',
            'waitDesc_1' => '可领取',
            'waitDesc_2' => '金币',
            'waitDesc_3' => '金币可提现',
            'waitIcon'   => '',
            'title'      => '完成完善资料任务',
            'desc_1'     => '金币已存入你的账户',
            'desc_2'     => '金币可提现',
            'icon'       => '',
            'task_type'  => 'fix_profile'
        ]);

        HostTaskReward::addRecord($userId, 'fix_profile', 5);

        return true;
    }

    public static function coinCanWithdraw(int $userId): bool
    {
        if (self::checkPopDemonstrated($userId, self::CAN_WITHDRAW_POP)) {
            return true;
        }

        $lastWithdraw = Withdraw::checkFirstV2($userId);
        if ($lastWithdraw === false || $lastWithdraw !== null) {
            return true;
        }

        // 挂断消息
        Message::sendSlient($userId, 'WITHDRAW_CAN', [
            'icon' => '',
            'title' => '新人提现特权',
            'desc_1' => "你有5元现金待提现！",
            'desc_2' => "(立即到账)",
        ]);

        return true;
    }

    /**
     * 检查相关弹窗是否已经展示过
     * @param int $userId
     * @param int $popIndex
     * @return bool
     */
    public static function checkPopDemonstrated(int $userId, int $popIndex)
    {
        $popStatusKey = RedisKey::newGirlPopStatus($userId);

        $popStatus = (int)RedisUtil::get($popStatusKey);

        $popStatus = decbin($popStatus);
        $sLen = strlen($popStatus);
        if ($sLen < $popIndex) {
            $popStatus .= str_repeat('0', ($popIndex - $sLen));
        }

        $status = substr($popStatus, $popIndex - 1, 1);
        if ($status == 1) {
            return true;
        }

        $popStatus = substr_replace($popStatus, "1", $popIndex - 1, 1);

        $popStatus = bindec($popStatus);

        RedisUtil::set($popStatusKey, $popStatus, 3600 * 24 * 365);

        return false;
    }
}
